// 初始化列表
var grid_selector = "";
var $grid_selector = "";
var pager_selector = "";
var parent_column = "";
var colNames = "";
var widthFunc = "";
var colModels = "";
$(document).ready(function () {
    // alert(1);
    // alert($(window.parent.document).find('#portal_iframe').height());
    // 初始化列表
    grid_selector = '#grid-table';
    $grid_selector = $(grid_selector);
    pager_selector = '#grid-pager';
    parent_column = $grid_selector.closest('[class*="col-"]');
    colNames = [
        'KBP编码',
        'UNITID',
        'kbpPath',
        '资源分类',
        '资源名称'
    ];
    widthFunc = parent_column.width() / colNames.length;
    colModels = [
        {name: 'kbpCode', index: 'kbpCode', hidden: true},
        {name: 'unitId', index: 'unitId', hidden: true},
        {name: 'kbpPath', index: 'kbpPath', hidden: true},
        {name: 'kbpName', index: 'kbpName', hideWidth: 300},
        {name: 'typeName', index: 'typeName', hideWidth: 650}
    ];

    // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
    $(document).on('show.bs.modal', '.modal', function () {
        var zIndex = 1040 + (10 * $('.modal:visible').length);
        $(this).css('z-index', zIndex);
        setTimeout(function () {
            $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
        }, 0);
    }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
        initKbpTable();
    });

    //当前页面打开窗口的尺寸
    window.onresize = function () {
        changeFrameHeight();
    }
    changeFrameHeight();


});

function changeFrameHeight() {
    var mainIframeHeight = $(window).height();
    var systemViewIframeHeight = mainIframeHeight - 72;
    $('#systemViewIframe').height(systemViewIframeHeight);
}

function initKbpTable() {
    $grid_selector.jqGrid({
        url: ctx + '/KbpResourceData/queryPageListType',
        mtype: 'post',
        datatype: 'json',
        height: '100%',
        colNames: colNames,
        colModel: colModels,
        autowidth: true,
        altRows: true,
        rownumbers: true,
        viewrecords: true,
        multiselect: true,
        multiboxonly: true,
        rowNum: rowNum,
        rowList: rowList,
        sortname: 'typeId',
        pager: pager_selector,
        sortname: 'viewOrder',
        sortorder: 'asc',
        jsonReader: jsonReader,
        beforeRequest: function () {
            var sortName = $grid_selector.jqGrid('getGridParam', 'sortname');// 排序列
            var sortOrder = $grid_selector.jqGrid('getGridParam', 'sortorder');// 排序方式：desc、asc
            var kbpData = [];
            // console.log(kbpId);
            //kpbCode作为查询条件
            $.extend($grid_selector.getGridParam('postData'), {'kbpCode': kbpId});
            kbpData.sidx = sortName;
            kbpData.sord = sortOrder;
            // 获取KBP树节点
            var selectedItems = $('#kbpTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                kbpData['kbpCode'] = selectedItems[0].additionalParameters.id;
            } else {
                kbpData['kbpCode'] = null;
            }
        },
        loadComplete: function () {
            setTimeout(function () {
                $grid_selector.jqGrid('setGridParam', parent_column.width());
            }, 20);
        }
    });
}


$.launchDialog = function (id) {
    function launchModalWin(id) {
        $('#' + id).modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
    }

    return launchModalWin(id);
};

function isNotEmpty(obj) {
    if (obj != null && obj != '' && obj != undefined) {
        return true;
    }
    return false;
}


//======================================================

//KBP树
var remoteKbpDateSource = function (options, callback) {
    var self = this;
    var $data = null;
    var roleSelCode = $('#kbpTreeview').tree('selectedItems')[0];
    if (!("name" in options) && !("type" in options)) {
        callback({data: queryKbpData('0', roleSelCode)});//
        return;
    } else if ("type" in options && options.type == "folder") {
        if ("additionalParameters" in options && "children" in options.additionalParameters)
            $data = queryKbpData(options.additionalParameters.id, roleSelCode);//点击父节点，加载子节点
        else {
            $data = {}
        }//no data
    }
    if ($data != null) {//this setTimeout is only for mimicking some random delay
        callback({data: $data});
    }
};

//KBP树
function queryKbpData(parentCode, kbpCode) {
    var treeData = null;
    $.ajax({
        url: ctx + '/systemView/queryTreeData?number=' + Math.random(),
        async: false,
        type: 'post',
        dataType: 'json',
        data: {
            parentCode: parentCode,
            kbpCode: kbpCode
        },
        success: function (data) {
            if (data.success) {
                treeData = data.result;
            }
        }
    });
    return treeData;
}

// //资源
// var resource = function (options, callback) {
//     var self = this;
//     var $data = null;
//     var roleSelCode = $('#roleTreeview').tree('selectedItems')[0];
//     // var sonCode = $('#roleTreeview').tree('sonCode')[3];
//
//     if (!("name" in options) && !("type" in options)) {
//         callback({data: queryData('0', roleSelCode)});//
//         // callback({data: queryData('3', sonCode)});//
//         return;
//     } else if ("type" in options && options.type == "folder") {
//         if ("additionalParameters" in options && "children" in options.additionalParameters)
//             $data = queryData(options.additionalParameters.id, roleSelCode);//点击父节点，加载子节点
//         else {
//             $data = {}
//         }
//     }
//     if ($data != null) {
//         callback({data: $data});
//     }
// };
//
// //资源
// var KBP_ID = '10-10-20';
// var UNIT_ID = '10-10-20:10_118_4_231';
//
// // var TYPE_NAME = '财务管控数据库服务器';
// function queryData() {
//     var Data = null;
//     $.ajax({
//         url: ctx + '/QueryData/queryData?number=' + Math.random(),
//         async: false,
//         type: 'post',
//         dataType: 'json',
//         data: {
//             KBP_ID: KBP_ID,
//             UNIT_ID: UNIT_ID
//         },
//         success: function (data) {
//             var list = data.bg;
//             var tableStr1 = "";
//             if (list.length > 0) {
//                 for (var i = 0; i < list.length; i++) {
//                     tableStr1 += "<div><li title='" + list[i].TYPE_NAME + "'><span id='abc'>" + list[i].TYPE_NAME + "</span></li></div>";
//                 }
//             }
//             $("#table").append(tableStr1);
//             alert(tableStr1);
//             $("#abc").click(function () {
//
//                 alert("确定之前");
//
//             });
//             if (data.success) {
//                 Data = data.result;
//             }
//         }
//     });
//     alert("执行完毕");
// }

// require.config({
//     baseUrl: ctx + '/resource/plugins/echarts4',
//     paths: {
//         echarts: 'echarts',
//         roma: 'theme/roma',
//     }
// });
// require(
//     [
//         'echarts',
//         'roma'
//     ],

//     function (ec) {
//         ECharts = ec;
//         HostInformationViewController();//主机基本信息
//         host_ping_ybp = ECharts.init(document.getElementById('host_ping_ybp'), 'roma');//ping结果
//         queryHostPing();
//         host_syslog_ybp = ECharts.init(document.getElementById('host_syslog_ybp'), 'roma');//syslog状态
//         queryHostSyslog();
//         host_cpu_syl_zxt = ECharts.init(document.getElementById('host_cpu_syl_zxt'), 'roma');//CPU使用率
//         queryHostCpu();
//         host_cpu_dzt = ECharts.init(document.getElementById('host_cpu_dzt'), 'roma');//CPU倒状图
//         queryHostCpuDzt();
//         host_nc_syl_zxt = ECharts.init(document.getElementById('host_nc_syl_zxt'), 'roma');//物理内存使用率
//         queryHostNc();
//         host_nc_dzt = ECharts.init(document.getElementById('host_nc_dzt'), 'roma');//内存倒状图
//         queryHostNcDzt();
//         host_cp_syl_zxt = ECharts.init(document.getElementById('host_cp_syl_zxt'), 'roma');//磁盘总使用率
//         queryHostCp();
//         host_cp_dzt = ECharts.init(document.getElementById('host_cp_dzt'), 'roma');//磁盘倒状图
//         queryHostCpDzt();
//         host_wjxt_syl_zzt = ECharts.init(document.getElementById('host_wjxt_syl_zzt'), 'roma');//文件系统使用率
//         queryHostWjxt();
//         HostInformationViewCyxx();//主机信息概览
//     }
// );

var kbpId;
/*点击按钮展示KBP树的节点*/
$('#kbpSelBut').click(function () {
    $('#kbpTreeview').tree('destroy');
    $('#treeDiv').html('<ul id="kbpTreeview"></ul>');
    //加載KBP
    $('#kbpTreeview').ace_tree({
        dataSource: remoteKbpDateSource,
        loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
        'open-icon': 'ace-icon fa fa-chevron-down',
        'close-icon': 'ace-icon fa fa-chevron-right',
        'itemSelect': true,
        'folderSelect': false,
        'multiSelect': false,
        'selected-icon': null,
        'unselected-icon': null,
        'folder-open-icon': 'ace-icon tree-plus',
        'folder-close-icon': 'ace-icon tree-minus',
        'cacheItems': false
    }).on('selected.fu.tree', function (event, data) {
        //点击KBP子节点查询所包含的资源名称
        kbpId = data.selected[0].additionalParameters.id;
        // alert("事件");
        $("#grid-table").trigger("reloadGrid");
    });
    $.launchDialog('popup');
    //==========================================================================
    // //点击子节点加载资源
    // $('#kbpTreeview').on('selected.fu.tree', function (event, data) {
    //     if (!$.contains($(this).find('.tree-selected').parent(), $(this).find('.tree-selected').parent().find('ul .icon-folder'))) {
    //         // $('#kbpTreeview').find('#10-10-21').click(function () {
    //         // $('#kbpTreeview .tree-branch-children .tree-branch-children li').click(function () {
    //         $("#kbpTreeview").find("li").click(function (event) {
    //
    //             if ($(this).attr("id") != ($("kbpTreeview li:last-child").attr("id"))) {
    //
    //                 $(this).attr("id");
    //                 alert($(this).attr("id"));
    //                 // $('#table').html('<ul id="aa"></ul>');
    //                 // $('#table').append(TYPE_NAME);
    //                 // reloadJqGrid('json');
    //             } else if ($(this).attr("id") != ($("kbpTreeview li:last-child"))) {
    //
    //                 $(this).attr("id");
    //                 alert($("kbpTreeview li:last-child"));
    //             }
    //             //阻止事件冒泡  //event.stopPropagation();
    //             return false;
    //         });
    //     }
    //     console.log($(this).find('.tree-selected').parent().html());
    // });
    //=============================================================================

});


// // 重新加载jqGrid表格
// function KbpJqGrid(datatype) {
//     // alert("加载表格");
//     $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('KbpJqGrid', [{page: 1}]);
// }



/*点击保存触发的操作*/
$('#confirm').click(function () {
    //获取选中行的id
    var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
    if (rowIds == null || rowIds.length == 0) {
        $(this).dynamicPop('请选择要跳转的资源页面!');
    } else if (rowIds.length > 1) {
        $(this).dynamicPop(' 不能选择多条记录, 请选择一条记录!');
    } else {
        var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        $("#resourceName").val(rowData.typeName);
        var unitId = rowData.unitId;
        var kbpPath = rowData.kbpPath;
        var url = ctx +kbpPath+"/"+unitId;
        $('#systemViewIframe').attr('src', url);
        // 跳转页面成功后关闭该窗口
        $('#popup').modal('hide');
    }

});

//按钮事件
$(".but_").click(function(){
    var href = $('iframe').attr('src');
    if(href == "") {
        $(this).dynamicPop('请先选择资源!');
        return;
    }else{
        var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        var unitId = rowData.unitId;
        var kbpPath = rowData.kbpPath;
        var id = $(this).attr('id');
        var url = ctx +kbpPath+"/"+unitId+"/"+id;
        $('#systemViewIframe').attr('src', url);
       /* $.ajax({
            url:url,
            success:function (){
                $('#systemViewIframe').attr('src', url);
            }
        })*/

    }
});

